#!/usr/bin/env python
'''your explanation
'''
__AUTHOR__ = 'sykp241095@gmail.com'

import sys
import os
import logging
import time
import tarfile
from optparse import OptionParser

def check_file_exists(filename):
    return os.path.exists(filename) and os.path.isfile(filename)

def check_dir_exists(dirname):
    return os.path.exists(dirname) and os.path.isdir(dirname)

parser = OptionParser(usage = r'''%prog [options] args''', 
        description = '''tar and compress files to a target dir. \
such as yourpath/file.tar.gz. \
if there's a `yourpath/file.tar.gz' \
create a `yourpath/file-20110304.tar.gz' like file. 
else, create `file.tar.gz' ''')
parser.add_option('-f', '--filename', 
        help = 'filename, such as filename, the prefix of filename.tar.gz')
parser.add_option('-d', '--delimiter', 
        help = r'''delimiter, such as `-' in filename-20100304.tar.gz''', 
        default = '-')
parser.add_option('-c', '--command',
        help = r'''command, gzip or bz2''', default = 'gzip')
parser.add_option('-p', '--path',
        help = r'''path, target dir to store the .tar.gz/bz2 file''', 
        default = '.')
options, args = parser.parse_args()

filename = options.filename
delimiter = options.delimiter
command = options.command
path = options.path

if not filename:
    print r'''error: please provide a -f option to sepcify `filename' '''
    sys.exit(1)

if not check_dir_exists(path):
    print r'''error: path does't exist or it's not a dir '''
    sys.exit(1)

# decide suffix and tar mode
if command == 'gzip':
    suffix = '.tar.gz'
    mode = 'w:gz'
elif command == 'bzip2':
    suffix = '.tar.bz2'
    mode = 'w:bz2'
else:
    print r"error: the value of `-c' option must be gzip(default) or bzip2"
    sys.exit(1)

# make sure `path' ends with '/'
if not path.endswith('/'):
    path += '/'

def generate_abs_file_name():
    global path, filename, suffix
    old_file_path = path + filename + suffix
    if check_file_exists( old_file_path ):
        global delimiter
        date_str = time.strftime( '%Y%m%d', time.localtime() )
        return path + filename + delimiter + date_str + suffix
    else:
        return old_file_path

def main():
    global mode, args
    abs_file_name = generate_abs_file_name()
    tar = tarfile.open( abs_file_name, mode )
    for name in args: tar.add(name)
    tar.close()

if __name__ == '__main__':
    main()
